import threading
import time
from flask import Flask, render_template, Response
import cv2

from app.util.Vedio import Vedio


class Sentvedio(object):
    def __init__(self,url='./static/vedio/direact/direact102.avi'):
        # 通过opencv获取实时视频流
        self.video = cv2.VideoCapture(url)
        self.url = url

    def __del__(self):
        self.video.release()

    def seturl(self,url):
        self.video = cv2.VideoCapture(url)
        self.url = url

    def get_frame(self):
        if self.video.isOpened():
            #print("ok",1)
            success, image = self.video.read()
            #cv2.imshow(image,"img")
        else:
            #print("erro",1)
            return
        # use motion JPEG mod need jpg frame

        if success:
            #print("ok", 2)
            ret, jpeg = cv2.imencode('.jpg', image)
        else:
            #print("erro", 2)
            return

        if ret:
            #print("ok", 3)
            return jpeg.tobytes()
        else:
            #print("erro", 3)
            return



def gen(veo):
    #frame = veo.get_frame()
    print("sent")
    while veo:
        #print("frame sent")
        time.sleep(0.04)
        if veo:
            try:
                frame = veo.get_frame()
                if frame:
                    # generator函数输出视频流， 每次req的content类型是image/jpeg
                    yield (b'--frame\r\n'
                        b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
                else:
                    continue
            except:
                print("erro")
                continue

